﻿package com.moonshineproject.utils 
{
	import flash.filesystem.File;
	
	public class Utils 
	{
		
		public static function getDirectoryPathFor(file:File):String
		{
			for (var i:int = file.url.length-1; i > 0; i--)
			{
				if (file.url.charAt(i) == "/") break;
			}
			return file.url.substring(0, i+1); 
		} 
		
		
		/**
		 * Deserializes True and False strings to true and false Boolean values.
		 */
		public static function deserializeBoolean(o:Object):Boolean {
			var str:String = o.toString();
			return (str.toLowerCase() == "true") ? true:false;
		}
		/**
		 * Serializes a Boolean value into True or False strings.
		 */
		public static function serializeBoolean(b:Boolean):String {
			return b ? "True" : "False";
		}
		
		/**
		 * Deserialize a String value so it's null when empty
		 */
		public static function deserializeString(o:Object):String {
			var str:String = o.toString();
			if (str.length == 0) return null;
			return str;
		}
		
		/**
		 * Serialize a String value so it's empty when null
		 */
		public static function serializeString(str:String):String {
			return str ? str : "";
		}
		
		/**
		 * Serialize key-value pairs to FD-like XML elements using a template element
		 *  Example:
		 *		<option accessible="True" />
		 *		<option allowSourcePathOverlap="True" />
		 *		<option benchmark="True" />
		 *		<option es="True" />
		 *		<option locale="" />
		 */
		public static function serializePairs(pairs:Object, template:XML):XMLList {
			var list:XML = <xml/>;
			for (var key:String in pairs) {
				var node:XML = template.copy();
				node.@[key] = pairs[key];
				list.appendChild(node);
			}
			return list.children();
		}
		
		public static function fixSlashes(path:String):String
		{
			if (!path) return null;
			
			path = path.replace(/\//g, File.separator);
			path = path.replace(/\\/g, File.separator);
			
			return path;
		}
		
	}
}